package mobile.pubcrawler.ui;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import mobile.pubcrawler.Filter;
import mobile.pubcrawler.R;
import mobile.pubcrawler.model.DataModel;
import mobile.pubcrawler.model.DataModelLocation;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MapUI extends MapActivity{

	MapView mapView;
	List<Overlay> mapOverlays;
	Drawable drawable;
	MapItemizedOverlay itemizedOverlay;
	GeoPoint point;

	@Override
	public void onCreate(Bundle savedInstanceState) {



		//		Location start = new Location(LocationManager.GPS_PROVIDER); 
		//		start.setLatitude(52.505665);
		//		start.setLongitude(13.3398);

		point = new GeoPoint((int)(Filter.getInstance().getRelativeToLatitude() * 1000000), (int)(Filter.getInstance().getRelativeToLongitude() * 1000000));


		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setSatellite(false);
		mapView.setBuiltInZoomControls(true);
		MapController mc = mapView.getController();
		mc.setCenter(point);
		//		mc.setZoom(14);


		mapOverlays = mapView.getOverlays();

		ArrayList<DataModelLocation> selectedLocations = DataModel.getInstance().getSelectedLocations();

//		int lat1 = (int)(selectedLocations.get(0).getLatitude() * 1000000);
//		int lon1 = (int)(selectedLocations.get(0).getLongitude() * 1000000);
//		GeoPoint destpoint = new GeoPoint(lat1, lon1);
//		
//		DrawPath(point, destpoint, Color.BLUE, mapView);
//		
		
		//startpunkt zeichnen
		drawable = this.getResources().getDrawable(R.drawable.pin);
		itemizedOverlay = new MapItemizedOverlay(drawable);


		OverlayItem overlayitem = new OverlayItem(point, "Startpunkt", "Startpunkt");
		LocationOverlay startLocationOverlay = new LocationOverlay(point, 0);
		itemizedOverlay.addOverlay(overlayitem);
		mapOverlays.add(startLocationOverlay);

		for(int i = 1; i <= selectedLocations.size(); i++){
			for(DataModelLocation dml : selectedLocations){

				if(dml.getPosition() == i){
					int lat = (int)(dml.getLatitude() * 1000000);
					int lon = (int)(dml.getLongitude() * 1000000);
					GeoPoint destpoint = new GeoPoint(lat, lon);

					DrawPath(destpoint, point, Color.BLUE, mapView);


					String title = "" + i + ". " + dml.getName();
					overlayitem = new OverlayItem(destpoint, title, title);

					LocationOverlay locationOverlay = new LocationOverlay(destpoint, i);
					itemizedOverlay.addOverlay(overlayitem);

					mapOverlays.add(locationOverlay);

					point = destpoint;
				}

			}
		}

//		mapOverlays.add(itemizedOverlay);

		mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
		mc.setCenter(itemizedOverlay.getCenter());
		//		itemizedOverlay.dopopulate();
		//		mc.setCenter(itemizedOverlay.getCenter());
		//		mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());

	}


	private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
	{
		// connect to map web service
		StringBuilder urlString = new StringBuilder();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");//from
		urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
		urlString.append(",");
		urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
		urlString.append("&daddr=");//to
		urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
		urlString.append(",");
		urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
		urlString.append("&dirflg=w&ie=UTF8&0&om=0&output=kml");
		Log.d("xxx","URL="+urlString.toString());
		// get the kml (XML) doc. And parse it to get the coordinates(direction route).
		Document doc = null;
		HttpURLConnection urlConnection= null;
		URL url = null;
		try
		{ 
			url = new URL(urlString.toString());
			urlConnection=(HttpURLConnection)url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect(); 

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream()); 

			if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
			{
				//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
				String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
				Log.d("xxx","path="+ path);
				String [] pairs = path.split(" "); 
				String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
				// src
				GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
				mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
				GeoPoint gp1;
				GeoPoint gp2 = startGP; 
				for(int i=1;i<pairs.length;i++) // the last one would be crash
				{
					lngLat = pairs[i].split(",");
					gp1 = gp2;
					// watch out! For GeoPoint, first:latitude, second:longitude
					gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
					mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
					Log.d("xxx","pair:" + pairs[i]);
				}
				mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
			} 
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
	}

//	Read more: http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html#ixzz0etivKPHW


		@Override
		protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	class LocationOverlay extends com.google.android.maps.Overlay {

		GeoPoint p;
		int locationPosition;

		LocationOverlay(GeoPoint p, int locationPosition){
			super();
			this.p = p;
			this.locationPosition = locationPosition;
		}

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {

			super.draw(canvas, mapView, shadow);
			Paint black = new Paint();
			// Converts lat/lng-Point to OUR coordinates on the screen.
			Point myScreenCoords = new Point();
			mapView.getProjection().toPixels(p, myScreenCoords);
			//			paint.setStrokeWidth(1);
			black.setARGB(255, 0, 0, 0);
			black.setTextAlign(Align.CENTER);
			//			paint.setStyle(Paint.Style.STROKE);
			Paint white = new Paint();
			white.setARGB(255, 255, 255, 255);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
			canvas.drawBitmap(bmp, (myScreenCoords.x - 12), (myScreenCoords.y - 37), white);
			
			canvas.drawText(""+locationPosition, (float) (myScreenCoords.x - 2.5), (myScreenCoords.y - 22), black);
			
//			canvas.drawRect(new Rect((myScreenCoords.x - ((canvas.getWidth() / 4))),  (myScreenCoords.y), (myScreenCoords.x + ((canvas.getWidth() / 4))), (myScreenCoords.y + 10) + 5 ), white);
//			canvas.drawText(locationName, myScreenCoords.x, (myScreenCoords.y + 10), black);
			return true;
		}

	};


}
